package models

import (
	"errors"
	"time"
)

type PushMsg struct {
	Id        int       `json:"id"`
	Title     string    `json:"title"`
	Icon      string    `json:"icon"`
	Type      int       `json:"type"`
	Content   string    `json:"content"`
	Link      string    `json:"link"`
	Status    int       `json:"status"`
	CreatedAt time.Time `json:"created_at"`
}

func AddPushMsg(data map[string]interface{}) error {
	m := DB.Table("push_msg").Create(&PushMsg{
		Title:     data["title"].(string),
		Icon:      data["icon"].(string),
		Type:      data["type"].(int),
		Content:   data["content"].(string),
		Link:      data["link"].(string),
		CreatedAt: time.Now(),
		Status:    1,
	})
	if m.Error != nil {
		return errors.New(m.Error.Error())
	}

	return nil
}
func GetPushMsgs(page, limit int) (interface{}, *Paginator) {
	var res []*PushMsg
	m := DB.Table("push_msg").Order("id DESC")

	var count int
	m.Count(&count)
	paginate := NewPage(page, limit, count)

	err := m.Offset(paginate.Offset).Limit(paginate.Limit).Find(&res).Error
	if err != nil {
		return nil, nil
	}

	return res, &paginate
}
func GetPushMsg(id int) (pushMsg PushMsg) {
	DB.Table("push_msg").Where("id = ?", id).First(&pushMsg)
	return
}
func ExistPushMsgByID(id int) bool {
	var pushMsg PushMsg
	DB.Table("push_msg").Select("id").Where("id = ?", id).First(&pushMsg)

	if pushMsg.Id > 0 {
		return true
	}

	return false
}

func EditPushMsgByID(id int, data interface{}) bool {
	err := DB.Table("push_msg").Where("id = ?", id).Updates(data)
	if err.Error != nil {
		return false
	}
	return true
}

func DeletePushMsg(id int) bool {
	err := DB.Table("push_msg").Where("id = ?", id).Delete(PushMsg{})

	if err.Error != nil {
		return false
	}
	return true
}
